package com.yurun.employeemodule.service.Impl;

import com.yurun.commonapi.api.CommonResult;
import com.yurun.commonapi.pojo.Employee;
import com.yurun.commonapi.pojo.StudentDocument;
import com.yurun.commonapi.pojo.Teacher;
import com.yurun.employeemodule.mapper.EmployeeMapper;
import com.yurun.employeemodule.service.EmployeeService;
import com.yurun.orgpermissionmodule.mapper.OrgPermissionMapper;
import com.yurun.teacherorgmodule.mapper.TeacherMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.DigestUtils;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author lihao
 * @mail lihaohaocn@gmail.com
 * @Date 2021/8/4 10:25 下午
 */
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private OrgPermissionMapper permissionModuleMapper;


    @Override
    public Employee getEmployeeById(BigInteger employeeId) {
        Employee employee = employeeMapper.getEmployeeById(employeeId);
        if (employee != null) {
            return employee;
        }
        return null;
    }

    @Override
    public List<Employee> getBranchEmployeeInfo(BigInteger organizationId, BigInteger branchId) {
        List<Employee> list = employeeMapper.getBranchEmployeeInfo(organizationId,branchId);
        return list;
    }

    @Override
    public List<Employee> getAllEmployeeInfo(BigInteger organizationId) {
        List<Employee> list = employeeMapper.getAllEmployeeInfo(organizationId);
        return list;
    }

    @Override
    public List<Employee> getEmployeeList(String keyword, BigInteger branchId, BigInteger organizationId) {
        if ( keyword.equals("") && branchId.longValue() == 0) {
            return employeeMapper.getAllEmployeeInfo(organizationId);
        } else if (!keyword.equals("") && branchId.longValue() == 0) {
            return employeeMapper.getEmployeeByName(organizationId, keyword);
        } else if (keyword.equals("") && branchId.longValue() != 0) {
            return employeeMapper.getBranchEmployeeInfo(organizationId,branchId);
        }
        return employeeMapper.getEmployeeByIdAndName(organizationId, keyword, branchId);
    }

    @Override
    public BigInteger getEnumId(String placeNum) {
        Random random = new Random();
        StringBuilder result= new StringBuilder();
        for (int i=0;i<6;i++)
        {
            result.append(random.nextInt(10));
        }
        return BigInteger.valueOf(Long.parseLong(placeNum + result));
    }

    @Override
    @Transactional
    public int delEmployeeById(BigInteger employeeId) {
        Employee employee = new Employee();
        employee.setEmployeeId(employeeId);
        employee.setUpdateTime(new Date());

        try {
            employeeMapper.delEmployeeById(employee);
            employeeMapper.delTeacherByEmployeeId(employeeId);
            return 1;
        } catch (Exception e) {
            System.out.println("发生异常,进行手动回滚！");
            // 手动回滚事物
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }

        return 0;
    }

    @Override
    @Transactional
    public CommonResult addEmployee(Employee employee, String organizationId) {
        // 生成员工id
        BigInteger employeeId = getEnumId(organizationId.substring(0, 6));
        Integer flag_employeeId = employeeMapper.verifyEmployeeIdIsRepeat(employeeId);
        // 判断是否已存在该员工id
        while (flag_employeeId != null) {  // 已存在
            employeeId = getEnumId(organizationId.substring(0, 6));
            flag_employeeId = employeeMapper.verifyEmployeeIdIsRepeat(employeeId);
        }
        employee.setEmployeeId(employeeId);
        employee.setOrganizationId(BigInteger.valueOf(Long.parseLong(organizationId)));
        employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());
        employee.setEmployeePwd(setMD5PWD("123456"));

        try {
            // 新增员工
            employeeMapper.addEmployee(employee);
            employeeMapper.addEmployeeRole(employee);

            String[] arr = employee.getEmployeePosition().split(",");
            for (String value : arr) {  // 遍历前端传的职位
                System.out.println("包含");
                Teacher teacher = new Teacher();
                teacher.setEmployeeId(employee.getEmployeeId());
                teacher.setOrganizationId(employee.getOrganizationId());
                teacher.setBranchId(employee.getBranchId());
                teacher.setUpdateTime(new Date());
                teacher.setCreateTime(new Date());
                teacherMapper.delTeacherFor(employee.getEmployeeId());
                addTeacher(teacher, value);

            }
            return CommonResult.success("新增员工成功！");
        } catch (Exception e) {
            System.out.println("发生异常,进行手动回滚！");
            // 手动回滚事物
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return CommonResult.failed("新增员工失败！");

    }

    @Override
    public int editEmployee(Employee employee) {
        employee.setUpdateTime(new Date());
        String[] arr = employee.getEmployeePosition().split(",");
        for (String value : arr) {  // 遍历前端传的职位
            System.out.println("包含");
            Teacher teacher = new Teacher();
            teacher.setEmployeeId(employee.getEmployeeId());
            teacher.setOrganizationId(employee.getOrganizationId());
            teacher.setBranchId(employee.getBranchId());
            teacher.setUpdateTime(new Date());
            teacher.setCreateTime(new Date());
            teacherMapper.delTeacherFor(employee.getEmployeeId());
            addTeacher(teacher, value);

        }
        return employeeMapper.editEmployee(employee);
    }

    @Override
    public CommonResult resetEmployeePwd(BigInteger employeeId) {
        Employee employee = new Employee();
        employee.setEmployeeId(employeeId);
        employee.setEmployeePwd(setMD5PWD("123456"));
        if (employeeMapper.resetEmployeePwd(employee) == 1) {
            return CommonResult.success("修改成功！");
        }
        return CommonResult.success("修改失败！");
    }

    @Override
    public CommonResult editEmployeePwd(BigInteger employeeId, String employeePwd, String newEmployeePwd) {
        try {
            String pwd = employeeMapper.getEmployeePwd(employeeId);
            if (pwd.equals(setMD5PWD(employeePwd))) {
                Employee employee = new Employee();
                employee.setEmployeeId(employeeId);
                employee.setEmployeePwd(setMD5PWD(newEmployeePwd));
                employee.setUpdateTime(new Date());
                employeeMapper.editEmployeePwd(employee);
                return CommonResult.success("修改成功！");
            } else {
                return CommonResult.failed("原密码输入错误！");
            }
        } catch (Exception e) {
            System.out.println("发生异常,进行手动回滚！");
            // 手动回滚事物
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }

        return CommonResult.failed("修改失败！");
    }

    @Override
    public CommonResult getOneClassroomInfo(BigInteger classroomId) {
        return CommonResult.success(employeeMapper.getOneClassroomInfo(classroomId));
    }

    @Transactional
    public void addPermission(int roleId, int[] arr) {
        // 增加权限
        for (int value : arr) {
            for (int list : employeeMapper.getAdminAllPermission(value)) {
                permissionModuleMapper.addPermissionByRoleId(roleId, list);
            }

        }
    }

    public void addTeacher(Teacher teacher, String flag) {
        if (flag.equals("2") || flag.equals("3") || flag.equals("4")) { // 教研组长
            // 增加权限
            int[] arr_teacher = {12};
            int roleId = employeeMapper.getRoleList(teacher.getEmployeeId()).get(0);
            teacher.setTeamId(Integer.parseInt(flag)); // 设置教研组
            addPermission(roleId, arr_teacher);
            teacherMapper.addTeacher(teacher);
        } else if (flag.equals("1")) {
            // 增加权限
            int[] arr_teacher = {10};
            int roleId = employeeMapper.getRoleList(teacher.getEmployeeId()).get(0);
            addPermission(roleId, arr_teacher);
            teacherMapper.addTeacher(teacher);
        }

    }

    public String setMD5PWD(String password){
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }
}